/*
 * @lc app=leetcode.cn id=79 lang=cpp
 *
 * [79] 单词搜索
 */

// @lc code=start
class Solution
{
    int m, n;
    int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

public:
    int dfs(vector<vector<char>> &board, string &word, vector<vector<int>> &mark, int i, int j, int len)
    {
        if (board[i][j] != word[len])
        {
            return 0;
        }
        if (len == word.size() - 1)
        {
            return 1;
        }
        mark[i][j] = 1;
        for (auto &d : dirs)
        {
            int ni = i + d[0];
            int nj = j + d[1];
            if (ni < 0 || ni >= m || nj < 0 || nj >= n || mark[ni][nj] == 1)
            {
                continue;
            }
            if (dfs(board, word, mark, ni, nj, len + 1))
            {
                return 1;
            }
        }
        mark[i][j] = 0;
        return 0;
    }
    bool exist(vector<vector<char>> &board, string word)
    {
        m = board.size(), n = board[0].size();
        vector<vector<int>> mark(m, vector<int>(n, 0));
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (board[i][j] == word[0])
                {
                    if (dfs(board, word, mark, i, j, 0))
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
};
// @lc code=end
